package upload

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gookit/event"
	"io/ioutil"
	"mime/multipart"
	"path"
	"vueBasic/extend/conv"
	"vueBasic/extend/utils"
	"vueBasic/global"
)

func Upload(file *multipart.FileHeader, rename string, c *gin.Context) (string, error) {
	//1、检验文件的大小
	if file.Size > conv.Int64(c.MustGet("filesize"))*1024*1024 {
		return "", errors.New("文件大小验证失败")
	}
	//2、检查文件后缀
	fileExt := path.Ext(file.Filename)
	if !utils.FileValid(fileExt, c.MustGet("filetype").(string)) {
		return "", errors.New("文件后缀验证失败")
	}
	var filepath string
	//3、这步主要用来判断文件是否要重新命名，不需要就忽略
	fileHandle, _ := file.Open()
	defer fileHandle.Close()
	body, err2 := ioutil.ReadAll(fileHandle)
	if err2 != nil {
		panic(err2)
	}
	hash := utils.Md5(string(body))
	var filename string
	if rename == "1" {
		filename = fmt.Sprintf("%s/%s%s", utils.GetSavePath(c), hash, fileExt)
	} else {
		filename = fmt.Sprintf("%s/%s", utils.GetSavePath(c), file.Filename)
	}
	switch global.CONF.Upload.Disks {
	case "local":
		filename = Local.Upload(file, filename, c)
	}
	//如果是本地，要拼接返回
	if global.CONF.Upload.Disks == "local" {
		filepath = c.MustGet("domain").(string) + filename
	} else {
		filepath = filename
	}
	//分发事件
	event.MustFire("afterUploadEvent", event.M{
		"filepath": filepath,
		"hash":     hash,
	})
	return filepath, nil
}
